# -*- coding: utf-8 -*-

from django.shortcuts import render_to_response
from django.contrib.auth.decorators import login_required
from django.http import HttpResponse, HttpResponseNotFound, HttpResponseForbidden

from django.contrib.gis.shortcuts import render_to_kml

from models import WMSBasemap, Tag, TinyMCE_File, TinyMCE_Image
from models import TinyMCE_Link, TinyMCE_Multimedia, TinyMCE_Template
from forms import TagForm


def homepage(request):
    if (str(request.user) == "AnonymousUser"):
        link = True
    else:
        link = False

    wms = WMSBasemap.objects.get(id=1)
    wms_layer = {"name":wms.name, "url":wms.url, "layers":wms.layers}
    return render_to_response("index.html",{ "wms_layer" : wms_layer, "link":link })
    
@login_required
def add_tag(request):
    if request.method == 'POST':
        form = TagForm(request.POST)
        if form.is_valid():
            name = form.cleaned_data['name']
            desc = form.cleaned_data['description']
            geo  = form.cleaned_data['geo']
            tag  = Tags(name=name,description=desc,geo=geo)
            tag.save()
            return 'OK'
        else:
            form = TagForm()
            wms = WMSBasemap.objects.get(id=1)
            wms_layer = {'name':wms.name,'url':wms.url,'layers':wms.layers}
            return render_to_response('add.html',{'wms_layer':wms_layer,'form':form})
    else:
        form = TagForm()
        wms = WMSBasemap.objects.get(id=1)
        wms_layer = {"name":wms.name, "url":wms.url, "layers":wms.layers}
        return render_to_response("add.html",{ "wms_layer":wms_layer,'form':form })

def tinymce(request,option):
    if option == 'images':
        images = TinyMCE_Image.objects.all()
        return render_to_response("tiny_mce/images.js",
                                  {"rows":images},
                                  mimetype="text/javascript")
    elif option == 'media':
        media = TinyMCE_Multimedia.objects.all()
        return render_to_response("tiny_mce/media.js",
                                  {"rows":media},
                                  mimetype="text/javascript")
    elif option == 'links':
        links = TinyMCE_Link.objects.all().order_by("name")
        files = TinyMCE_File.objects.all().order_by("name")
        return render_to_response("tiny_mce/links.js",
                                  {"rows1":links,
                                   "rows2":files},
                                  mimetype="text/javascript")
    elif option == 'templates':
        templates = TinyMCE_Template.objects.all()
        return render_to_response("tiny_mce/templates.js",
                                  {"rows":templates},
                                  mimetype="text/javascript")
    else:
        return HttpResponseForbidden()

def kml_tags(request):
    tags = Tag.objects.kml()
    return render_to_kml("gis/placemarks.kml",{"places": tags})
    


